import hashlib
import re
import time

import requests
from django.contrib.auth.hashers import make_password
from rest_framework.response import Response
from rest_framework.views import APIView

from tools.myjwt import myjwt
from user.models import UserModel, ThirdPartyLogin
from user.seriali import UserModelSerializers, ThirdPartyLoginSerializers


# Create your views here.
class DingTalkLogin(APIView):
    def get(self, request):
        from urllib.parse import quote
        params = [
            f"redirect_uri={quote('http://localhost:5173/#/pages/home/blank')}",
            "response_type=code",
            "client_id=dingrwtalu8jpcndyfvi",
            "scope=openid",
            "prompt=consent"
        ]
        url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        return Response({"url": url})

class DingTalkCallback(APIView):
    def get(self, request):
        authCode = request.query_params.get('code')
        print("===============")
        print(authCode)
        # 根据authCode获取用户accessToken
        data = {
            "clientId": "dingrwtalu8jpcndyfvi",
            "clientSecret": "XZnk4q_iLOSGqVCHST_txijqeYKlq5xbpH4RaLpimFec-jGpqsxkOIdWGHcNbHYz",
            "code": authCode,
            "grantType": "authorization_code"
        }
        resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        accessToken = resp.get('accessToken')

        # 根据accessToken获取用户信息
        headers = {"x-acs-dingtalk-access-token": accessToken}
        resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()

        nikename = resp.get('nick')
        uid = resp.get('openId')
        mobile = resp.get('mobile')
        print(nikename, uid, mobile,accessToken)

        # # 登录，写入三方登录表和用户表
        sfl = ThirdPartyLogin.objects.filter(uid=uid, types=0).first()
        if not sfl:
            # 写入用户表
            # 手机号用户存在直接绑定,不存在注册新用户
            user = UserModel.objects.filter(mobile=mobile).first()
            if not user:
                userinfo = {
                    "nikename": nikename,
                    "mobile": mobile,
                    "password": mobile,
                }
                us = UserModelSerializers(data=userinfo)
                # 检查序列化器us是否有效
                if us.is_valid():
                    user = us.save()
                else:
                    return Response({"code": 10001, "msg": "用户信息序列化错误","data": us.errors})
            # 写入三方登录表
            Thirdinfo = {
                "types": 0,
                "token": accessToken,
                "uid": uid,
                "userid": user.id
            }
            sfs = ThirdPartyLoginSerializers(data=Thirdinfo)
            if sfs.is_valid():
                sfs.save()
            else:
                return Response({"code": 10001, "msg": "三方登录序列化错误","data": sfs.errors})
        else:
            user = sfl.userid
            # sfl.token = accessToken
            # sfl.save()

        # 生成jwt token并返回前端
        payload = {"user_id": user.id, "exp": int(time.time()) + 60 * 60 * 2,"mobile":user.mobile}
        token = myjwt.jwt_encode(payload)
        payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
        refreshToken = myjwt.jwt_encode(payload)
        query = [f"userid={payload['user_id']}", f"token={token}",f"mobile={mobile}"
                 f"refreshToken={refreshToken}"]
        return Response({"code": 200, "token": token})
        # return Response({"code": 200, "token": "token"})


class RegisterView(APIView):
    def post(self, request):
        nikename = request.data.get("nikename")
        password = request.data.get("password")
        mobile = request.data.get("mobile")
        if not all([nikename, password, mobile]):
            return Response({"code": 10001, "msg": "请输入完整信息"})
        elif UserModel.objects.filter(mobile=mobile).first():
            return Response({"code": 10002, "msg": "手机号已注册"})
        elif UserModel.objects.filter(nikename=nikename).exists():
            return Response({"code": 10003, "msg": "昵称已存在"})
        elif not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({"code": 10004, "msg": "手机号格式不正确"})
        else:
            encrypted_password = make_password(password)
            # print(encrypted_password)
            user = UserModel.objects.create(nikename=nikename, password=encrypted_password, mobile=mobile)
            res = UserModelSerializers(user)
            return Response({"code": 200, "msg": "注册成功,请登录","user": res.data})